import axios from "axios";
// import { MessageBox, Message } from "element-ui";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/modules/user";
import router from "../router";
// import { getToken } from "@/utils/auth";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      // config.headers.Authorization = `Bearer ${userStore.token}`;
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  (error) => {
    // 请求初始化错误（如参数错误）
    ElMessage.error("请求参数异常，请检查");
    return Promise.resolve(error || null);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code === 401) {
      ElMessage.error("登录已过期，请重新登录");
      router.push({
        path: "/login",
      });
      return Promise.resolve(null);
    }
    if (res.code !== 200) {
      ElMessage({ message: res.msg, type: "warning" });
      return Promise.resolve(res || null);
    }
    return res;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401: {
          ElMessage.error("登录已过期，请重新登录");
          router.push({ path: "/login" });
          return Promise.resolve({ code: 401 });
        }
        case 404:
          console.error("接口地址不存在，请核对请求路径：", error.config.url);
          break;
        case 500:
          ElMessage.error("服务器内部错误，请联系管理员");
          break;
      }
    } else if (error.request) {
      ElMessage.error("网络连接失败，请检查网络");
    }
    // return Promise.reject(error);
    return Promise.resolve({ code: 401 });
  }
);

export default service;
